

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  
    <meta name="description" content="如果是做Python或者其他语言的小伙伴，对于生成器应该不陌生。但很多PHP开发者或许都不知道生成器这个功能，可能是因为生成器是PHP 5.5.0才引入的功能，也可以是生成器作用不是很明显。但是，生成器功能的确非常有用。 优点直接讲概念估计你听完还是一头雾水，所以我们先来说说优点，也许能勾起你的兴趣。那么生成器有哪些优点，如下：  生成器会对PHP应用的性能有非常大的影响 PHP代码运行时节省大量">
<meta property="og:type" content="article">
<meta property="og:title" content="【转】PHP中被忽略的性能优化利器：生成器.md">
<meta property="og:url" content="http://example.com/2018/10/25/php/PHP%E4%B8%AD%E8%A2%AB%E5%BF%BD%E7%95%A5%E7%9A%84%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E5%88%A9%E5%99%A8%EF%BC%9A%E7%94%9F%E6%88%90%E5%99%A8-md/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="如果是做Python或者其他语言的小伙伴，对于生成器应该不陌生。但很多PHP开发者或许都不知道生成器这个功能，可能是因为生成器是PHP 5.5.0才引入的功能，也可以是生成器作用不是很明显。但是，生成器功能的确非常有用。 优点直接讲概念估计你听完还是一头雾水，所以我们先来说说优点，也许能勾起你的兴趣。那么生成器有哪些优点，如下：  生成器会对PHP应用的性能有非常大的影响 PHP代码运行时节省大量">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://example.com/images/php/yield1.png">
<meta property="og:image" content="http://example.com/images/php/yield2.png">
<meta property="og:image" content="http://example.com/images/php/bootstrap.png">
<meta property="og:image" content="http://example.com/images/php/yield3.png">
<meta property="og:image" content="http://example.com/images/php/yield4.png">
<meta property="article:published_time" content="2018-10-25T07:32:51.000Z">
<meta property="article:modified_time" content="2022-02-10T03:11:37.976Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="PHP">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="http://example.com/images/php/yield1.png">
  
  
  <title>【转】PHP中被忽略的性能优化利器：生成器.md - Hexo</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.8.13","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 6.0.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>LZDF</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="【转】PHP中被忽略的性能优化利器：生成器.md">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2018-10-25 15:32" pubdate>
        2018年10月25日 下午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      4.4k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      37 分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">【转】PHP中被忽略的性能优化利器：生成器.md</h1>
            
            <div class="markdown-body">
              <p>如果是做Python或者其他语言的小伙伴，对于生成器应该不陌生。但很多PHP开发者或许都不知道生成器这个功能，可能是因为生成器是PHP 5.5.0才引入的功能，也可以是生成器作用不是很明显。但是，生成器功能的确非常有用。</p>
<h1 id="优点"><a href="#优点" class="headerlink" title="优点"></a>优点</h1><p>直接讲概念估计你听完还是一头雾水，所以我们先来说说优点，也许能勾起你的兴趣。那么生成器有哪些优点，如下：</p>
<ul>
<li>生成器会对PHP应用的性能有非常大的影响</li>
<li>PHP代码运行时节省大量的内存</li>
<li>比较适合计算大量的数据</li>
</ul>
<p>那么，这些神奇的功能究竟是如何做到的？我们先来举个例子。</p>
<h1 id="概念引入"><a href="#概念引入" class="headerlink" title="概念引入"></a>概念引入</h1><p>首先，放下生成器概念的包袱，来看一个简单的PHP函数：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createRange</span>(<span class="hljs-params"><span class="hljs-variable">$number</span></span>)</span>&#123;<br>    <span class="hljs-variable">$data</span> = [];<br>    <span class="hljs-keyword">for</span>(<span class="hljs-variable">$i</span>=<span class="hljs-number">0</span>;<span class="hljs-variable">$i</span>&lt;<span class="hljs-variable">$number</span>;<span class="hljs-variable">$i</span>++)&#123;<br>        <span class="hljs-variable">$data</span>[] = time();<br>    &#125;<br>    <span class="hljs-keyword">return</span> <span class="hljs-variable">$data</span>;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>这是一个非常常见的PHP函数，我们在处理一些数组的时候经常会使用。这里的代码也非常简单：</p>
<ul>
<li>1、我们创建一个函数。</li>
<li>2、函数内包含一个for循环，我们循环的把当前时间放到$data里面</li>
<li>3、for循环执行完毕，把$data返回出去。</li>
</ul>
<p>下面没完，我们继续。我们再写一个函数，把这个函数的返回值循环打印出来：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;start time: &#x27;</span> . <span class="hljs-variable">$start_time</span> = microtime_float();<br><br><span class="hljs-variable">$result</span> = createRange(<span class="hljs-number">10</span>); <span class="hljs-comment">// 这里调用上面我们创建的函数</span><br><span class="hljs-keyword">foreach</span>(<span class="hljs-variable">$result</span> <span class="hljs-keyword">as</span> <span class="hljs-variable">$value</span>)&#123;<br>    sleep(<span class="hljs-number">1</span>);<span class="hljs-comment">//这里停顿1秒，我们后续有用</span><br>    <span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;&lt;br&gt;&#x27;</span> . <span class="hljs-variable">$value</span>;<br>&#125;<br><br><span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;&lt;br&gt; end time: &#x27;</span> . <span class="hljs-variable">$end_time</span> = microtime_float();<br><span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;&lt;br&gt; 当前页面执行时间： &#x27;</span> . (<span class="hljs-variable">$end_time</span> - <span class="hljs-variable">$start_time</span>);<br></code></pre></td></tr></table></figure>
<p>这里定义了一个辅助函数，用于打印程序的执行时间：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * 返回微妙数（辅助函数）</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@return</span> float</span><br><span class="hljs-comment"> */</span><br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">microtime_float</span>(<span class="hljs-params"></span>)</span><br><span class="hljs-function"></span>&#123;<br>    <span class="hljs-keyword">list</span>(<span class="hljs-variable">$usec</span>, <span class="hljs-variable">$sec</span>) = explode(<span class="hljs-string">&#x27; &#x27;</span>, microtime());<br>    <span class="hljs-keyword">return</span> <span class="hljs-variable">$usec</span> + <span class="hljs-variable">$sec</span>;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>我们在浏览器里面看一下运行结果：</p>
<p><img src="/images/php/yield1.png" srcset="/img/loading.gif" lazyload alt="普通数组方法返回结果"></p>
<p>这里非常完美，没有任何问题。</p>
<h1 id="思考一个问题"><a href="#思考一个问题" class="headerlink" title="思考一个问题"></a>思考一个问题</h1><p>我们注意到，在调用函数 <code>createRange</code> 的时候给 <code>$number</code> 的传值是10，一个很小的数字。假设，现在传递一个值 <code>10000000</code>（1000万）。</p>
<p>那么，在函数 <code>createRange</code> 里面，<code>for</code> 循环就需要执行 <code>1000</code>万次。且有 <code>1000</code> 万个值被放到 <code>$data</code> 里面，而 <code>$data</code> 数组在是被放在内存内。所以，在调用函数时候会占用大量内存。</p>
<p>这里，生成器就可以大显身手了。</p>
<h1 id="创建生成器"><a href="#创建生成器" class="headerlink" title="创建生成器"></a>创建生成器</h1><p>我们直接修改代码，你们注意观察：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createRange</span>(<span class="hljs-params"><span class="hljs-variable">$number</span></span>)</span>&#123;<br>    <span class="hljs-keyword">for</span>(<span class="hljs-variable">$i</span>=<span class="hljs-number">0</span>;<span class="hljs-variable">$i</span>&lt;<span class="hljs-variable">$number</span>;<span class="hljs-variable">$i</span>++)&#123;<br>        <span class="hljs-keyword">yield</span> time();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>看下这段和刚刚很像的代码，我们删除了数组 <code>$data</code>，而且也没有返回任何内容，而是在 <code>time()</code> 之前使用了一个关键字 <code>yield</code></p>
<h1 id="使用生成器"><a href="#使用生成器" class="headerlink" title="使用生成器"></a>使用生成器</h1><p>我们再运行一下第二段代码：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;start time: &#x27;</span> . <span class="hljs-variable">$start_time</span> = microtime_float();<br><br><span class="hljs-variable">$result</span> = createRange(<span class="hljs-number">10</span>); <span class="hljs-comment">// 这里调用上面我们创建的函数</span><br><span class="hljs-keyword">foreach</span>(<span class="hljs-variable">$result</span> <span class="hljs-keyword">as</span> <span class="hljs-variable">$value</span>)&#123;<br>    sleep(<span class="hljs-number">1</span>);<span class="hljs-comment">//这里停顿1秒，我们后续有用</span><br>    <span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;&lt;br&gt;&#x27;</span> . <span class="hljs-variable">$value</span>;<br>&#125;<br><br><span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;&lt;br&gt; end time: &#x27;</span> . <span class="hljs-variable">$end_time</span> = microtime_float();<br><span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;&lt;br&gt; 当前页面执行时间： &#x27;</span> . (<span class="hljs-variable">$end_time</span> - <span class="hljs-variable">$start_time</span>);<br></code></pre></td></tr></table></figure>

<p><img src="/images/php/yield2.png" srcset="/img/loading.gif" lazyload alt="使用生成器返回结果"></p>
<p>我们奇迹般的发现了，输出的值和第一次没有使用生成器的不一样。这里的值（时间戳）中间间隔了1秒。</p>
<p>这里的间隔一秒其实就是 <code>sleep(1)</code> 造成的后果。但是为什么第一次没有间隔？那是因为：</p>
<ul>
<li>未使用生成器时：<code>createRange</code> 函数内的 <code>for</code> 循环结果被很快放到 <code>$data</code>中，并且立即返回。所以，<code>foreach</code> 循环的是一个固定的数组。</li>
<li>使用生成器时：<code>createRange</code> 的值不是一次性快速生成，而是依赖于 <code>foreach</code> 循环。<code>foreach</code> 循环一次，<code>for</code> 执行一次。</li>
</ul>
<p>到这里，你应该对生成器有点儿头绪。</p>
<h1 id="深入理解生成器"><a href="#深入理解生成器" class="headerlink" title="深入理解生成器"></a>深入理解生成器</h1><h2 id="代码剖析"><a href="#代码剖析" class="headerlink" title="代码剖析"></a>代码剖析</h2><p>下面我们来对于刚刚的代码进行剖析（去掉冗余部分）。</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createRange</span>(<span class="hljs-params"><span class="hljs-variable">$number</span></span>)</span>&#123;<br>    <span class="hljs-keyword">for</span>(<span class="hljs-variable">$i</span>=<span class="hljs-number">0</span>;<span class="hljs-variable">$i</span>&lt;<span class="hljs-variable">$number</span>;<span class="hljs-variable">$i</span>++)&#123;<br>        <span class="hljs-keyword">yield</span> time();<br>    &#125;<br>&#125;<br><br><span class="hljs-variable">$result</span> = createRange(<span class="hljs-number">10</span>); <span class="hljs-comment">// 这里调用上面我们创建的函数</span><br><span class="hljs-keyword">foreach</span>(<span class="hljs-variable">$result</span> <span class="hljs-keyword">as</span> <span class="hljs-variable">$value</span>)&#123;<br>    sleep(<span class="hljs-number">1</span>);<br>    <span class="hljs-keyword">echo</span> <span class="hljs-variable">$value</span>.<span class="hljs-string">&#x27;&lt;br /&gt;&#x27;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>我们来还原一下代码执行过程。</p>
<ul>
<li>首先调用 <code>createRange</code> 函数，传入参数 <code>10</code>，但是 <code>for</code> 值执行了一次然后停止了，并且告诉 <code>foreach</code> 第一次循环可以用的值。</li>
<li><code>foreach</code> 开始对 <code>$result</code> 循环，进来首先 <code>sleep(1)</code>，然后开始使用 <code>for</code> 给的一个值执行输出。</li>
<li><code>foreach</code> 准备第二次循环，开始第二次循环之前，它向 <code>for</code> 循环又请求了一次。</li>
<li><code>for</code> 循环于是又执行了一次，将生成的时间戳告诉<code>foreach</code>.</li>
<li><code>foreach</code> 拿到第二个值，并且输出。由于 <code>foreach</code> 中 <code>sleep(1)</code>，所以，<code>for</code> 循环延迟了1秒生成当前时间</li>
</ul>
<p>所以，整个代码执行中，始终只有一个记录值参与循环，内存中也只有一条信息。</p>
<p>无论开始传入的 <code>$number</code> 有多大，由于并不会立即生成所有结果集，所以内存始终是一条循环的值。</p>
<h1 id="概念理解"><a href="#概念理解" class="headerlink" title="概念理解"></a>概念理解</h1><p>到这里，你应该已经大概理解什么是生成器了。下面我们来说下生成器原理。</p>
<p>首先明确一个概念：<strong>生成器yield关键字不是返回值，他的专业术语叫<code>产出值</code>，只是生成一个值</strong></p>
<p>那么代码中 <code>foreach</code> 循环的是什么？其实是PHP在使用生成器的时候，会返回一个 <code>Generator</code> 类的对象。<code>foreach</code> 可以对该对象进行迭代，每一次迭代，PHP会通过 <code>Generator</code> 实例计算出下一次需要迭代的值。这样 <code>foreach</code> 就知道下一次需要迭代的值了。</p>
<p>而且，在运行中 <code>for</code> 循环执行后，会立即停止。等待 <code>foreach</code> 下次循环时候再次和 <code>for</code> 索要下次的值的时候，<code>for</code> 循环才会再执行一次，然后立即再次停止。直到不满足条件不执行结束。</p>
<h1 id="实际开发应用"><a href="#实际开发应用" class="headerlink" title="实际开发应用"></a>实际开发应用</h1><p>很多PHP开发者不了解生成器，其实主要是不了解应用领域。那么，生成器在实际开发中有哪些应用？</p>
<h2 id="读取超大文件"><a href="#读取超大文件" class="headerlink" title="读取超大文件"></a>读取超大文件</h2><p>PHP开发很多时候都要读取大文件，比如csv文件、text文件，或者一些日志文件。这些文件如果很大，比如5个G。这时，直接一次性把所有的内容读取到内存中计算不太现实。</p>
<p>这里生成器就可以派上用场啦。简单看个例子：读取log文件</p>
<p><img src="/images/php/bootstrap.png" srcset="/img/loading.gif" lazyload alt="bootstrap.log"></p>
<p>这是我系统的一个启动日志，拿来做示范读取</p>
<ul>
<li><p>通过数组输出文件内容</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><code class="hljs php">header(<span class="hljs-string">&quot;content-type:text/html;charset=utf-8&quot;</span>);<br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">readLog</span>(<span class="hljs-params"></span>)</span><br><span class="hljs-function"></span>&#123;<br>    <span class="hljs-comment"># code...</span><br>    <span class="hljs-variable">$handle</span> = fopen(<span class="hljs-string">&quot;./bootstrap.log&quot;</span>, <span class="hljs-string">&#x27;rb&#x27;</span>);<br><br>    <span class="hljs-variable">$data</span> = [];<br>    <span class="hljs-keyword">while</span> (feof(<span class="hljs-variable">$handle</span>)===<span class="hljs-literal">false</span>) &#123;<br>        <span class="hljs-comment"># code...</span><br>        <span class="hljs-variable">$data</span>[] = fgets(<span class="hljs-variable">$handle</span>);<br>    &#125;<br><br>    fclose(<span class="hljs-variable">$handle</span>);<br>    <span class="hljs-keyword">return</span> <span class="hljs-variable">$data</span>;<br>&#125;<br><br><span class="hljs-variable">$start_time</span> = microtime_float();<br><span class="hljs-variable">$start_mem</span> = memory_get_usage();<br><br><span class="hljs-variable">$result</span> = readLog();<br><span class="hljs-keyword">foreach</span> (<span class="hljs-variable">$result</span> <span class="hljs-keyword">as</span> <span class="hljs-variable">$key</span> =&gt; <span class="hljs-variable">$value</span>) &#123;<br>    <span class="hljs-comment"># code...</span><br>    <span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;&lt;br&gt;&#x27;</span> . <span class="hljs-variable">$value</span>;<br>&#125;<br><br><span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;start time: &#x27;</span> . <span class="hljs-variable">$start_time</span>;<br><span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;&lt;br&gt;end time: &#x27;</span> . <span class="hljs-variable">$end_time</span> = microtime_float();<br><span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;&lt;br&gt;读取文件总共用时: &#x27;</span> . (<span class="hljs-variable">$end_time</span> - <span class="hljs-variable">$start_time</span>);<br><br><span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;&lt;br&gt;start memory: &#x27;</span> . <span class="hljs-variable">$start_mem</span>;<br><span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;&lt;br&gt;end memory: &#x27;</span> . <span class="hljs-variable">$end_mem</span> = memory_get_usage();<br><span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;&lt;br&gt;total memory: &#x27;</span> . (<span class="hljs-variable">$end_mem</span> - <span class="hljs-variable">$start_mem</span>) / <span class="hljs-number">1024</span>;<br></code></pre></td></tr></table></figure>
<p><img src="/images/php/yield3.png" srcset="/img/loading.gif" lazyload alt="使用数组返回结果"></p>
</li>
<li><p>通过生成器输出文件内容</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs php">...<br>...<br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">readLog</span>(<span class="hljs-params"></span>)</span><br><span class="hljs-function"></span>&#123;<br>    <span class="hljs-comment"># code...</span><br>    <span class="hljs-variable">$handle</span> = fopen(<span class="hljs-string">&quot;./bootstrap.log&quot;</span>, <span class="hljs-string">&#x27;rb&#x27;</span>);<br><br>    <span class="hljs-variable">$data</span> = [];<br>    <span class="hljs-keyword">while</span> (feof(<span class="hljs-variable">$handle</span>)===<span class="hljs-literal">false</span>) &#123;<br>        <span class="hljs-comment"># code...</span><br>        <span class="hljs-keyword">yield</span> = fgets(<span class="hljs-variable">$handle</span>);<br>    &#125;<br><br>    fclose(<span class="hljs-variable">$handle</span>);<br>&#125;<br>...<br>...<br></code></pre></td></tr></table></figure>
<p><img src="/images/php/yield4.png" srcset="/img/loading.gif" lazyload alt="使用生成器返回结果"></p>
</li>
</ul>
<p>通过上图的输出结果我们可以看出：</p>
<p><strong>输出的内容完全相同，但使用数组输出文件内容和使用生成器输出内容所占用的内存差距很惊人</strong>（我这个文件大小为：300.8k）。</p>
<p>由此可见，两种方式背后的代码执行规则一点儿也不一样。使用生成器读取文件，第一次读取了第一行，第二次读取了第二行，以此类推，<strong>每次被加载到内存中的文字只有一行</strong>，大大的减小了内存的使用。</p>
<p>这样，即使读取上G的文本也不用担心，完全可以像读取很小文件一样编写代码。</p>
<p>【注】：本传转载自<a target="_blank" rel="noopener" href="https://segmentfault.com/a/1190000012334856">PHP中被忽略的性能优化利器：生成器</a></p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/PHP/">PHP</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/PHP/">PHP</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2018/10/29/php/%E4%B8%80%E9%81%93%E7%9C%8B%E4%BC%BC%E7%AE%80%E5%8D%95%E7%9A%84%E9%9D%A2%E8%AF%95%E9%A2%98/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">【转】一道看似简单的面试题</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2018/10/23/php/PHP%E5%AE%9E%E7%8E%B0%E5%BC%82%E6%AD%A5%E8%B0%83%E7%94%A8%E6%96%B9%E6%B3%95/">
                        <span class="hidden-mobile">【转】PHP实现异步调用方法</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  

  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
